package com.dzh.matrix;

import java.util.Scanner;

/**
 * @Author 戴志豪
 * @date 2022/10/7 20:12
 */
public class SpiralMatrix {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please input a number: ");
        // 层数
        int n = scanner.nextInt();
        // 初始化矩阵
        int[][] num = new int[n][n];

        // 定义行列，及计数器
        int row = 0, col = 0;
        int count = 1;

        // 定义信号量
        int flag = 0;

        // 定义方位数组, 顺序：右，下，左，上
        int[][] direction = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

        while (count != n * n + 1) {


            if (((row + direction[flag][0] > n - 1) || (row + direction[flag][0] < 0)) ||       // row的下一步如果越界，即转向
                            ((col + direction[flag][1] > n - 1) || (col + direction[flag][1] < 0)) ||   // col的下一步如果越界，即转向
                            (num[row + direction[flag][0]][col + direction[flag][1]] != 0)) {   // 如果下一个位置已经有值，也转向
                flag = (flag + 1) % 4;
            }

            num[row][col] = count;

            row = row + direction[flag][0];
            col = col + direction[flag][1];

            count++;
        }

        // 输出矩阵
        for (int[] ints : num) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }


    }

}
